﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetroFramework.Forms;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Collections;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Net.Mime.MediaTypeNames;

namespace sn_scan
{
    public partial class MainForm : MetroForm
    {
        private ArrayList lableList = new ArrayList();
        private ArrayList snList = new ArrayList();
        int index = 0;
        int sum = 0;

        public MainForm()
        {
            InitializeComponent();
        }


        private void textBoxSN_KeyUp(object sender, KeyEventArgs e)
        {
            string sn = textBoxSN.Text;


            int pos = sn.IndexOf('\r');
            if (-1 != pos || e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(sn))
                {
                    return;
                }

                if (index == GlobeData.num)
                {
                    MessageBox.Show("条码数量已满，请重置");
                    return;
                }

                if (GetASn(sn))
                {
                    textBoxSN.Text = "";
                    textBoxSN.Focus();
                }
            }

            //if (e.KeyCode == Keys.Enter)
            //{
            //    if (string.IsNullOrEmpty(sn))
            //    {
            //        return;
            //    }

            //    if (index == GlobeData.num)
            //    {
            //        MessageBox.Show("条码数量已满，请重置");
            //        return;
            //    }

            //    if (GetASn(sn))
            //    {
            //        textBoxSN.Text = "";
            //        textBoxSN.Focus();
            //    }
            //}
        }

        private bool GetASn(string sn)
        {

            if (sn.Length != GlobeData.len )
            {
                MessageBox.Show(string.Format("条码不符合设置规范，设定长度为{0},获取的长度为{1}", GlobeData.len, sn.Length));
                return false;
            }

            if (!sn.StartsWith(GlobeData.startWith))
            {
                MessageBox.Show(string.Format("条码不符合设置规范，开始字符{0},获取的开始字符为{1}", GlobeData.startWith, sn.Substring(0, GlobeData.startWith.Length)));
                return false;
            }

            for (int i = 0; i < snList.Count; i++)
            {
                if ((string)snList[i] == sn)
                {
                    MessageBox.Show(string.Format("条码重复扫描", GlobeData.startWith, sn.Substring(sn.Length)));
                    textBoxSN.Text = "";
                    return false;
                }
            }

            ListViewItem item = new ListViewItem();
            item.SubItems[0].Text = DateTime.Now.ToString();
            item.SubItems.Add(sn);
            listViewSNRecord.Items.Add(item);

            if (!writeCsv(item.SubItems[0].Text + "," + sn))
            {
                return false;
            }

            snList.Add(sn);

            Label l = (Label)lableList[index];
            l.BackColor = Color.Red;
            index++;
            sum++;
            textBoxSNNum.Text = sum.ToString();

            return true;
        }

        private bool writeCsv(string data)
        {
            string csvPath = string.Format("{0}\\report\\{1}", GlobeData.appPath, GlobeData.configName);
            string csvFilePath = string.Format("{0}\\report\\{1}\\record.csv", GlobeData.appPath, GlobeData.configName);

            if (!Directory.Exists(csvPath))
            {
                Directory.CreateDirectory(csvPath);
            }

            FileStream w = null;
            StreamWriter writer = null;
            if (!File.Exists(csvFilePath))
            {
                w = File.Create(csvFilePath);
                w.Close();
                writer = new StreamWriter(csvFilePath, true);
                writer.WriteLine("dt,sn");
            }
            else
            {
                writer = new StreamWriter(csvFilePath, true);
            }

            writer.WriteLine(data);
            writer.Close();

            return true;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            GlobeData.appPath = Utils.GetCurrentPath();

            GetConfig();

            DrawUi();

            ReadCsv();
        }

        private void ReadCsv()
        {
            string csvPath = string.Format("{0}\\report\\{1}", GlobeData.appPath, GlobeData.configName);
            string csvFilePath = string.Format("{0}\\report\\{1}\\record.csv", GlobeData.appPath, GlobeData.configName);

            if (!Directory.Exists(csvPath))
            {
                Directory.CreateDirectory(csvPath);
            }

            FileStream w = null;
            StreamWriter writer = null;
            if (!File.Exists(csvFilePath))
            {
                w = File.Create(csvFilePath);
                w.Close();
                return;
            }

            StreamReader reader = new StreamReader(csvFilePath);
            string lin = string.Empty;
            while ((lin = reader.ReadLine()) != null)
            {
                snList.Add(lin.Split(',')[1]);
            }

            reader.Close();

            StreamWriter stream = new StreamWriter(csvFilePath);
            stream.WriteLine("开始时间,条码");
            stream.Close();
        }

        private void DrawUi()
        {

            if (lableList.Count > 0)
            {
                for (int i = 0; i < lableList.Count; i++)
                {
                    Label l = (Label)lableList[i];
                    l.Dispose();
                }
                lableList.Clear();
            }

            int len = 50;
            int maxx = 0, maxy = 0;
            for (int i = 0; i < GlobeData.num; i++)
            {
                Label label = new Label();
                label.Text = (i + 1).ToString();
                label.Visible = true;
                label.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                label.TextAlign = ContentAlignment.MiddleCenter;
                label.Size = new System.Drawing.Size(len, len);
                int x = (i % 6) * (len + 10) + label1.Left;
                int y = (i / 6) * (len + 10) + listViewSNRecord.Top;

                maxx = maxx > x ? maxx : x;
                maxy = maxy > y ? maxy : y;

                label.Location = new System.Drawing.Point(x, y);
                this.Controls.Add(label);
                label.Name = "lableUI" + i.ToString();
                label.Show();
                lableList.Add(label);
            }

            for (int i = 0; i < index; i++)
            {
                Label l = (Label)lableList[i];
                l.BackColor = Color.Red;
            }
        }

        private void GetConfig()
        {
            string model = Utils.ReadConfig("model");

            if (string.IsNullOrEmpty(model))
            {
                MessageBox.Show("配置文件读错误，请重试");
                return;
            }

            GlobeData.configName = model;

            string iniPath = GlobeData.appPath + "\\conf\\" + model + "\\SN.ini";

            GlobeData.startWith = Utils.INIRead("SN", "startText", iniPath);
            string v = Utils.INIRead("SN", "snLenth", iniPath);
            string v1 = Utils.INIRead("SN", "snNum", iniPath);

            GlobeData.len = 0;
            GlobeData.num = 0;
            try
            {

                GlobeData.len = Convert.ToInt32(v);
                GlobeData.num = Convert.ToInt32(v1);
            }
            catch (Exception ex)
            {
                MessageBox.Show("读配置文件SN错误");
                return;
            }
        }

        private void ToolStripMenuItemChangeModel_Click(object sender, EventArgs e)
        {
            new ModelForm().ShowDialog();
            //GetConfig();
            //DrawUi();
        }

        private void ToolStripMenuItemConfig_Click(object sender, EventArgs e)
        {
            new SNSetForm().ShowDialog();
            DrawUi();
        }

        private void buttonR_Click(object sender, EventArgs e)
        {
            index = 0;
            for (int i = 0; i < lableList.Count; i++)
            {
                Label l = (Label)lableList[i];

                l.BackColor = Color.White;
            }
            textBoxSN.Text = string.Empty;
            textBoxSN.Focus();
        }
    }
}
